package com.daocao.hua.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.daocao.hua.R;
import com.daocao.hua.adapter.EarnMoneyAdapter;
import com.daocao.hua.adapter.TabTopAdapter;
import com.daocao.hua.api.Api;
import com.daocao.hua.api.bean.SpreadListsBean;
import com.daocao.hua.constant.Const;
import com.daocao.hua.model.SpreadIndexModel;
import com.daocao.hua.util.AppBarStateChangeListener;
import com.daocao.hua.util.Network;
import com.daocao.hua.util.OnLoadeMoreListener;
import com.daocao.hua.util.RxLifeUtil;
import com.daocao.hua.util.Spans;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.BannerLayout;
import com.daocao.hua.view.V19FrameLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/6/10.
 */

public class EarnMoneyActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.tablayout)
    RecyclerView tablayout;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.btn_tips)
    SuperButton btnTips;
    @BindView(R.id.btn_upload)
    SuperButton btnUpload;
    @BindView(R.id.txt_number)
    TextView txtNumber;
    @BindView(R.id.banner)
    BannerLayout banner;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.layout_empty)
    LinearLayout layoutEmpty;
    @BindView(R.id.collapsing_toolbar)
    CollapsingToolbarLayout collapsingToolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.main_content)
    CoordinatorLayout mainContent;
    private Unbinder unbinder;
    private TabTopAdapter TabAdapter;
    private EarnMoneyAdapter adapter;
    private String isJingHua = "1";
    private List<String> photoUrl = new ArrayList<>();
    private SpreadIndexModel.DataBean.ExternalLinksBean external_links;
    private OnLoadeMoreListener onLoadeMoreListener = new OnLoadeMoreListener() {
        @Override
        public void onLoadMore(int page) {
            getSpreadLists(page);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_earn_money);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
    }

    private void init() {
        setIsNeedCheckLogout(false);
        txtTitle.setText("推广赚钱");
//        txtRight.setText("我的推广");
//        txtRight.setVisibility(View.VISIBLE);

        TabAdapter = new TabTopAdapter(this);
        TabAdapter.setOnChooseListener(new TabTopAdapter.OnChooseListener() {
            @Override
            public void onClick(int poi) {
                if (poi == 0) {
                    isJingHua = "1";
                } else {
                    isJingHua = "0";
                }
                onLoadeMoreListener.setPage();

                getSpreadLists(1);
            }
        });
        tablayout.setLayoutManager(new GridLayoutManager(this, 2));
        tablayout.setAdapter(TabAdapter);
        List<String> tab_titles = new ArrayList<>();
        tab_titles.add("精华帖");
        tab_titles.add("全部帖子");
        TabAdapter.update(tab_titles);

        appbar.addOnOffsetChangedListener(new

                                                  AppBarStateChangeListener() {
                                                      @Override
                                                      public void onStateChanged(AppBarLayout appBarLayout, State state) {

                                                      }

                                                      @Override
                                                      public void onRefresh(int offset) {
                                                          //初始verticalOffset为0，不能参与计算。
                                                          if (offset >= 0) {
                                                              refresh.setEnabled(true);
                                                          } else {
                                                              refresh.setEnabled(false);
                                                          }
                                                      }
                                                  });
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                onLoadeMoreListener.setPage();
                getSpreadLists(1);
                getSpreadIndex();
            }
        });
        adapter = new EarnMoneyAdapter(this);
        list.addOnScrollListener(onLoadeMoreListener);
        list.setAdapter(adapter);
        getSpreadLists(1);
        getSpreadIndex();
    }

    public void getSpreadIndex() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);

        Api.api_service.getSpreadIndex().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    external_links = result.data.external_links;
                    Spanned number = Spans.with(this).font("累计获奖", getResources().getDimensionPixelSize(R.dimen.x30), 0xff616185).
                            font(result.data.statistics.people, getResources().getDimensionPixelSize(R.dimen.x34), 0xff27293E).style(Typeface.BOLD).
                            font("人", getResources().getDimensionPixelSize(R.dimen.x30), 0xff616185).
                            build();
                    txtNumber.setText(number);

                    if (result.data.banners.size() != 0 && photoUrl.size() == 0) {
                        photoUrl.clear();
                        for (int i = 0, bannerSize = result.data.banners.size(); i < bannerSize; i++) {
                            photoUrl.add(result.data.banners.get(i).image);
                        }

                        banner.setViewUrls(photoUrl);
                        banner.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                            @Override
                            public void onItemClick(int position) {
                                if (UI.isFastClick()) {
                                    return;
                                }
                                Intent intent = new Intent(EarnMoneyActivity.this, LookPayProcessActivity.class);
                                intent.putExtra(Const.KEY.PROCESS_URL, result.data.banners.get(position).url);
                                intent.putExtra("title", "推广");
                                startActivity(intent);
                            }
                        });
                        if (result.data.banners.size() == 1) {
                            banner.stopAutoPlay();
                        }
                    }

                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        banner.startAutoPlay();
    }

    @Override
    protected void onPause() {
        super.onPause();
        banner.stopAutoPlay();
    }

    public void getSpreadLists(int page) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);
        SpreadListsBean bean = new SpreadListsBean();
        bean.page = page;
        if (isJingHua.equals("1")) {
            bean.is_elite = isJingHua;
        }

        Api.api_service.getSpreadLists(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    adapter.add(result.data.lists, page == 1);

                    if (adapter.getItemCount() == 0) {
                        layoutEmpty.setVisibility(View.VISIBLE);
                    } else {
                        layoutEmpty.setVisibility(View.GONE);
                        if (page == 1) {
                            list.smoothScrollToPosition(0);
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        unbinder = null;
    }

    @OnClick({R.id.btn_share, R.id.btn_back, R.id.btn_my_earn_money, R.id.btn_tips, R.id.btn_upload,R.id.btn_xinyongka, R.id.btn_huafei})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_share:
                if (Util.checkLogin(this))
                    Util.startActivity(this, V3InviteFriendsActivity.class);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_my_earn_money:
                if (Util.checkLogin(this)) {
                    Util.startActivity(this, MyExtensionActivity.class);
                }
                break;
            case R.id.btn_tips:
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "推广攻略");
                intent.putExtra("url", Const.ACT_SPREAD);
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_upload:
                if (Util.checkLogin(this)) {
                    Util.startActivity(this, V3UploadTypeActivity.class);
                }
                break;
            case R.id.btn_xinyongka:
                if (external_links == null || external_links.credit_card == null || external_links.credit_card.enable == 0) {
                    ToastUtil.makeText(this, "敬请期待");
                    return;
                }
                Intent intent2 = new Intent(this, WebViewActivity.class);
                intent2.putExtra("title", "申请信用卡");
                intent2.putExtra("url", external_links.credit_card.links);
                startActivity(intent2);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_huafei:
                if (external_links == null || external_links.telephone == null || external_links.telephone.enable == 0) {
                    ToastUtil.makeText(this, "敬请期待");
                    return;
                }
                Intent intent1 = new Intent(this, WebViewActivity.class);
                intent1.putExtra("title", "话费充值");
                intent1.putExtra("url", external_links.telephone.links);
                startActivity(intent1);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
        }
    }
}
